package chencb.stu.thrift.client;

import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import java.lang.reflect.Constructor;

import static com.sun.corba.se.impl.util.RepositoryId.cache;

public class BaseUtils {
    public static TServiceClient getClient(String className) throws Exception {
        String host = "127.0.0.1";
        int port = 7920;
        int timeout = 50000;
        TTransport tTransport = new TSocket(host, port, timeout);
        TFramedTransport tFramedTransport = new TFramedTransport(tTransport);
        tFramedTransport.open();
        TBinaryProtocol protocol = new TBinaryProtocol(tFramedTransport);
        TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, className);

        Class cl = Class.forName(className + "$Client");
        Constructor<?> constructor = cl.getDeclaredConstructor(org.apache.thrift.protocol.TProtocol.class);
        TServiceClient client = (TServiceClient) constructor.newInstance(multiplexedProtocol);
        return client;
    }

    public static TServiceClient getClientWithnio(String className){
        String host = "127.0.0.1";
        int port = 7940;
        int timeout = 50000;

        TFramedTransport transport = null;
        try {
            transport = new TFramedTransport(new TSocket(host, port, timeout));
            transport.open();
            // 协议要和服务端一致
            TBinaryProtocol protocol = new TBinaryProtocol(transport);
            TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, className);

            Class cl = Class.forName(className + "$Client");
            Constructor<?> constructor = cl.getDeclaredConstructor(org.apache.thrift.protocol.TProtocol.class);
            TServiceClient client = (TServiceClient) constructor.newInstance(multiplexedProtocol);
            return client;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
